package com.easychat.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.easychat.entity.config.AppConfig;
import com.easychat.entity.constants.Constants;
import com.easychat.entity.enums.AppUpdateFileTypeEnum;
import com.easychat.entity.enums.AppUpdateStatusEnum;
import com.easychat.entity.enums.ResponseCodeEnum;
import com.easychat.exception.BusinessException;
import org.springframework.stereotype.Service;

import com.easychat.entity.enums.PageSize;
import com.easychat.entity.query.AppUpdateQuery;
import com.easychat.entity.po.AppUpdate;
import com.easychat.entity.vo.PaginationResultVO;
import com.easychat.entity.query.SimplePage;
import com.easychat.mappers.AppUpdateMapper;
import com.easychat.service.AppUpdateService;
import com.easychat.utils.StringTools;
import org.springframework.web.multipart.MultipartFile;


/**
 * app发布 业务接口实现
 */
@Service("appUpdateService")
public class AppUpdateServiceImpl implements AppUpdateService {
	@Resource
	private AppConfig appConfig;

	@Resource
	private AppUpdateMapper<AppUpdate, AppUpdateQuery> appUpdateMapper;

	/**
	 * 根据条件查询列表
	 */
	@Override
	public List<AppUpdate> findListByParam(AppUpdateQuery param) {
		return this.appUpdateMapper.selectList(param);
	}

	/**
	 * 根据条件查询列表
	 */
	@Override
	public Integer findCountByParam(AppUpdateQuery param) {
		return this.appUpdateMapper.selectCount(param);
	}

	/**
	 * 分页查询方法
	 */
	@Override
	public PaginationResultVO<AppUpdate> findListByPage(AppUpdateQuery param) {
		int count = this.findCountByParam(param);
		int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

		SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
		param.setSimplePage(page);
		List<AppUpdate> list = this.findListByParam(param);
		PaginationResultVO<AppUpdate> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
		return result;
	}

	/**
	 * 新增
	 */
	@Override
	public Integer add(AppUpdate bean) {
		return this.appUpdateMapper.insert(bean);
	}

	/**
	 * 批量新增
	 */
	@Override
	public Integer addBatch(List<AppUpdate> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.appUpdateMapper.insertBatch(listBean);
	}

	/**
	 * 批量新增或者修改
	 */
	@Override
	public Integer addOrUpdateBatch(List<AppUpdate> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.appUpdateMapper.insertOrUpdateBatch(listBean);
	}

	/**
	 * 多条件更新
	 */
	@Override
	public Integer updateByParam(AppUpdate bean, AppUpdateQuery param) {
		StringTools.checkParam(param);
		return this.appUpdateMapper.updateByParam(bean, param);
	}

	/**
	 * 多条件删除
	 */
	@Override
	public Integer deleteByParam(AppUpdateQuery param) {
		StringTools.checkParam(param);
		return this.appUpdateMapper.deleteByParam(param);
	}

	/**
	 * 根据Id获取对象
	 */
	@Override
	public AppUpdate getAppUpdateById(Integer id) {
		return this.appUpdateMapper.selectById(id);
	}

	/**
	 * 根据Id修改
	 */
	@Override
	public Integer updateAppUpdateById(AppUpdate bean, Integer id) {
		return this.appUpdateMapper.updateById(bean, id);
	}

	/**
	 * 根据Id删除
	 */
	@Override
	public Integer deleteAppUpdateById(Integer id) {
		if (AppUpdateStatusEnum.GRAYSCALE.getStatus().equals(this.getAppUpdateById(id).getStatus())) {
			throw new BusinessException("灰度发布版本不能删除");
		}
		return this.appUpdateMapper.deleteById(id);
	}

	/**
	 * 根据Version获取对象
	 */
	@Override
	public AppUpdate getAppUpdateByVersion(String version) {
		return this.appUpdateMapper.selectByVersion(version);
	}

	/**
	 * 根据Version修改
	 */
	@Override
	public Integer updateAppUpdateByVersion(AppUpdate bean, String version) {
		return this.appUpdateMapper.updateByVersion(bean, version);
	}

	/**
	 * 根据Version删除
	 */
	@Override
	public Integer deleteAppUpdateByVersion(String version) {
		return this.appUpdateMapper.deleteByVersion(version);
	}
	@Override
	public void saveUpdate(AppUpdate appUpdate, MultipartFile file) throws IOException {
		//找到相应的枚举类型
		AppUpdateFileTypeEnum fileTypeEnum = AppUpdateFileTypeEnum.getByType(appUpdate.getFileType());
		if (null == fileTypeEnum) {
			throw new BusinessException("文件类型错误");
		}

		//灰度版本不能修改，防止绕
		if (AppUpdateStatusEnum.GRAYSCALE.getStatus().equals(appUpdate.getStatus())) {
			throw new BusinessException("灰度发布版本不能修改");
		}

		//新版本号必须大于旧版本号 :设置按id降序 然后取第一条
		AppUpdateQuery appUpdateQuery = new AppUpdateQuery();
		appUpdateQuery.setOrderBy("id desc");
		appUpdateQuery.setSimplePage(new SimplePage(0, 1));
		List<AppUpdate> list = appUpdateMapper.selectList(appUpdateQuery);
		if (!list.isEmpty()) {
			AppUpdate lastestAppUpdate = list.get(0);
			Long dbVersion = Long.parseLong(lastestAppUpdate.getVersion().replace(".", ""));
			Long curVersion = Long.parseLong(appUpdate.getVersion().replace(".", ""));


			if (appUpdate.getId() == null && dbVersion >= curVersion) {
				throw new BusinessException("新版本号必须大于旧版本号");
			}
			//修改版本号 可能并没有修改版本号，即版本号没有变化，但是其他内容可能有变化
			if (appUpdate.getId() != null && curVersion >= dbVersion && !appUpdate.getId().equals(lastestAppUpdate.getId())) {
				throw new BusinessException("新版本号必须大于旧版本号");
			}
			AppUpdate versionDb = appUpdateMapper.selectByVersion(appUpdate.getVersion());
			if (appUpdate.getId()!=null && versionDb!=null && !appUpdate.getId().equals(versionDb.getId())) {
				throw new BusinessException("版本号重复");
			}


		}

		//新增
		if (appUpdate.getId() == null) {
			appUpdate.setCreateTime(new Date());
			appUpdate.setStatus(AppUpdateStatusEnum.INIT.getStatus());
			appUpdateMapper.insert(appUpdate);

		} else {
			//更新操作不应该更新这两个字段 这两个字段只有在发布新版本时才会被设置，设置为null防止造成误改
			appUpdate.setStatus(null);
			appUpdate.setGrayscaleUid(null);
			appUpdateMapper.updateById(appUpdate, appUpdate.getId());

		}


		//存储文件
		if (file != null) {
			//							D:/EasyJavaCode/file/appUpdate/
			File folder = new File(appConfig.getProjectFolder() + Constants.APP_UPDATE_FOLDER);
			if (!folder.exists()) {
				folder.mkdirs();
			}
			file.transferTo(new File(folder.getAbsolutePath() + "/" + appUpdate.getId() + Constants.APP_EXE_SUFFIX));
		}


	}

	@Override
	public void postUpdate(Integer id, String status, String grayscaleUid) {
		AppUpdateStatusEnum statusEnum = AppUpdateStatusEnum.getByStatus(status);
		if(null==statusEnum){
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}
		//是灰度发布，则必须设置灰度用户
		if (statusEnum.equals(AppUpdateStatusEnum.GRAYSCALE )&& grayscaleUid==null){
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}
		//不是灰度发布，则不能设置灰度用户
		if (AppUpdateStatusEnum.GRAYSCALE!=statusEnum){
			grayscaleUid="";
		}
		AppUpdate appUpdate = appUpdateMapper.selectById(id);
		appUpdate.setStatus(statusEnum.getStatus());
		appUpdate.setGrayscaleUid(grayscaleUid);

		appUpdateMapper.updateById(appUpdate, id);


	}

    @Override
    public AppUpdate getLatestUpdate(String appVersion, String uid) {
		return appUpdateMapper.selectLatestUpdate(appVersion, uid);

	}
}